"use strict";
cc._RF.push(module, '8e80dMWyH5LD7Oj100K42f8', 'Game');
// Scripts/Game.js

'use strict';

var Fruit = cc.Class({
    name: 'FruitItem',
    properties: {
        id: 0,
        iconSF: cc.SpriteFrame
    }
});

var JuiceItem = cc.Class({
    name: 'JuiceItem',
    properties: {
        particle: cc.SpriteFrame,
        circle: cc.SpriteFrame,
        slash: cc.SpriteFrame
    }
});

var ATJSSDK = require("./AnyThinkAds/ATJSSDK");
var ATRewardedVideoJSSDK = require("./AnyThinkAds/ATRewardedVideoJSSDK");
cc.Class({
    extends: cc.Component,

    properties: {
        fruits: {
            default: [],
            type: Fruit },

        juices: {
            default: [],
            type: JuiceItem
        },

        // 动态生成 找到批量处理预置元素的方案
        fruitPrefab: {
            default: null,
            type: cc.Prefab
        },

        juicePrefab: {
            default: null,
            type: cc.Prefab
        },

        // todo 可以实现一个audioManager
        boomAudio: {
            default: null,
            type: cc.AudioClip
        },
        knockAudio: {
            default: null,
            type: cc.AudioClip
        },
        waterAudio: {
            default: null,
            type: cc.AudioClip
        }
    },

    openVideo: function openVideo() {},
    onTouchStart: function onTouchStart(t) {
        if (this.isOpen_remove == true) {
            return;
        }
        //水果在下落中禁止移动
        if (this.isCreating == true) {
            return;
        }
        var pos = t.getLocation();
        var size = cc.winSize;
        var x = pos.x,
            y = pos.y;

        x = x - size.width / 2;
        this.currentFruit.position = cc.v2(x, this.currentFruit.position.y);
    },
    initAds: function initAds() {},
    onLoad: function onLoad() {
        this.initAds();
        this.speed = 1;
        this.node.getChildByName("overBg").active = false;
        this.gmAuto = true;
        this.isOpen_remove = false;
        this.node.getChildByName("background").getChildByName("right").active = true;
        this.node.getChildByName("background").getChildByName("score").active = true;
        this.node.getChildByName("background").getChildByName("tip").active = false;
        this.initPhysics();
        this.clickGm();
        this.c_score = 0;
        this.refScore();
        this.isCreating = false;
        this.fruitCount = 0;

        //设置line
        var size = cc.winSize;
        var y = size.height / 2 - 300;
        this.node.getChildByName("background").getChildByName("line").position = cc.v2(0, y);
        this.node.getChildByName("background").getChildByName("line").active = false;

        // 监听点击事件 todo 是否能够注册全局事件
        var self = this;
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);

        //根据触摸位置移动当前水果坐标
        this.node.on(cc.Node.EventType.TOUCH_MOVE, function (t) {
            if (self.isOpen_remove == true) {
                return;
            }

            //水果在下落中禁止移动
            if (self.isCreating == true) {
                return;
            }
            var pos = t.getLocation();
            var size = cc.winSize;
            var x = pos.x,
                y = pos.y;

            x = x - size.width / 2;
            this.currentFruit.position = cc.v2(x, this.currentFruit.position.y);
            self.currentFruit.getChildByName("tuowei").active = false;
        }, this);

        this.node.on(cc.Node.EventType.TOUCH_END, function (t) {
            //参数：移除某个道具，正常流程掉落
            if (self.isOpen_remove == true) {
                var size = cc.winSize;
                var p = cc.v2(t.getLocation().x - size.width / 2, t.getLocation().y - size.height / 2);
                self.findContains(p);
            } else {
                // self.currentFruit.getChildByName("tuowei").active = true;
                self.currentFruit.getChildByName("tuowei").active = false;
                self.onTouchEnd(t);
            }
        }, this), this.node.on(cc.Node.EventType.TOUCH_CANCEL, function (t) {
            //参数：移除某个道具，正常流程掉落
            if (self.isOpen_remove == true) {
                var size = cc.winSize;
                var p = cc.v2(t.getLocation().x - size.width / 2, t.getLocation().y - size.height / 2);
                self.findContains(p);
            } else {
                // self.currentFruit.getChildByName("tuowei").active = true;
                self.currentFruit.getChildByName("tuowei").active = false;
                self.onTouchEnd(t);
            }
        }, this), this.initOneFruit();
    },
    clickGm: function clickGm() {
        this.gmAuto = !this.gmAuto;
        if (this.gmAuto == true) {
            this.node.getChildByName("background").getChildByName("auto").getChildByName("v").getComponent(cc.Label).string = "已开启持续生成";
        } else {
            this.node.getChildByName("background").getChildByName("auto").getChildByName("v").getComponent(cc.Label).string = "已关闭持续生成";
        }
    },
    clickSpeed: function clickSpeed() {
        if (this.speed == 1) {
            this.speed = 0.8;
        } else if (this.speed == 0.8) {
            this.speed = 0.5;
        } else if (this.speed == 0.5) {
            this.speed = 0.2;
        } else {
            this.speed = 1;
        }
        this.node.getChildByName("background").getChildByName("create").getChildByName("v").getComponent(cc.Label).string = "生成速度：" + this.speed;
    },
    findContains: function findContains(p) {
        var f = this.node.getChildByName("fruits");
        var isH = false;
        for (var i = 0; i < f.childrenCount; i++) {
            if (i <= f.childrenCount - 1) {
                var node_box = f.getChildren()[i].getBoundingBox();
                if (node_box.contains(p) == true) {
                    if (isH == false && f.getChildren()[i].uuid != this.currentFruit.uuid) {
                        f.getChildren()[i].destroy();
                        cc.audioEngine.play(this.boomAudio, false, 1);
                        cc.audioEngine.play(this.waterAudio, false, 1);
                        // 展示动画
                        var juice = cc.instantiate(this.juicePrefab);
                        this.node.addChild(juice);
                        var _f$getChildren$i = f.getChildren()[i],
                            x = _f$getChildren$i.x,
                            y = _f$getChildren$i.y;

                        var config = this.juices[0];
                        var instance = juice.getComponent('Juice');
                        instance.init(config);
                        instance.showJuice(cc.v2({ x: x, y: y }), f.getChildren()[i].width);
                        isH = true;
                    }
                }
            }
        }

        if (isH == true) {
            this.isCreating = false;
            this.isOpen_remove = false;
            this.node.getChildByName("background").getChildByName("right").active = true;
            this.node.getChildByName("background").getChildByName("score").active = true;
            this.node.getChildByName("background").getChildByName("tip").active = false;
        }
    },
    refScore: function refScore() {
        this.node.getChildByName("background").getChildByName("score").getComponent(cc.Label).string = this.c_score;
    },


    // 开启物理引擎和碰撞检测
    initPhysics: function initPhysics() {
        // 物理引擎
        var instance = cc.director.getPhysicsManager();
        instance.enabled = true;
        // instance.debugDrawFlags = 4
        instance.gravity = cc.v2(0, -960);

        // 碰撞检测
        var collisionManager = cc.director.getCollisionManager();
        collisionManager.enabled = true;

        // 设置四周的碰撞区域
        var width = this.node.width;
        var height = this.node.height;

        var node = new cc.Node();

        var body = node.addComponent(cc.RigidBody);
        body.type = cc.RigidBodyType.Static;

        var _addBound = function _addBound(node, x, y, width, height) {
            var collider = node.addComponent(cc.PhysicsBoxCollider);
            collider.offset.x = x;
            collider.offset.y = y;
            collider.size.width = width;
            collider.size.height = height + 300;
        };

        _addBound(node, 0, -height / 2, width, 1);
        _addBound(node, 0, height / 2, width, 1);
        _addBound(node, -width / 2, 0, 1, height);
        _addBound(node, width / 2, 0, 1, height);

        node.parent = this.node;
    },
    initOneFruit: function initOneFruit() {
        var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;

        this.fruitCount++;
        var size = cc.winSize;
        var y = size.height / 2 - 200;
        this.currentFruit = this.createFruitOnPos(0, y, id);

        this.findPos();
    },


    // 监听屏幕点击
    onTouchEnd: function onTouchEnd(e) {
        var _this = this;

        if (this.isCreating) return;
        this.isCreating = true;
        var _node = this.node,
            width = _node.width,
            height = _node.height;


        var fruit = this.currentFruit;

        var pos = e.getLocation();
        var x = pos.x,
            y = pos.y;

        x = x - width / 2;
        // y = y - height / 2


        if (this.isOpen_remove == true) {
            return;
        }

        //        const action = cc.sequence(cc.moveBy(0.3, cc.v2(x, fruit.position.y)).easing(cc.easeCubicActionIn()), cc.callFunc(() => {
        // 开启物理效果
        this.startFruitPhysics(fruit);

        var self = this;
        // 1s后重新生成一个
        this.scheduleOnce(function () {
            self.currentFruit.getChildByName("tuowei").active = false;
            var nextId = _this.getNextFruitId();
            _this.initOneFruit(nextId);
            _this.isCreating = false;
            if (self.gmAuto == true) {
                _this.onTouchEnd(e);
            }
        }, self.speed);

        // const action = cc.sequence(cc.callFunc(() => {

        // }))
        // fruit.runAction(action)
    },


    // 获取下一个水果的id
    getNextFruitId: function getNextFruitId() {
        if (this.fruitCount < 3) {
            return 1;
        } else if (this.fruitCount === 3) {
            return 2;
        } else {
            // 随机返回前5个
            return Math.floor(Math.random() * 5) + 1;
        }
    },


    //检查线
    findPos: function findPos() {
        var isDie = false;
        this.node.getChildByName("background").getChildByName("line").active = false;
        console.log(this.currentFruit.position);

        var f = this.node.getChildByName("fruits");
        for (var i = 0; i < f.childrenCount; i++) {
            if (f.getChildren()[i].uuid != this.currentFruit.uuid) {
                if (f.getChildren()[i].position.y > 100) {
                    this.node.getChildByName("background").getChildByName("line").active = true;
                    var size = cc.winSize;
                    var y = size.height / 2 - 300;
                    if (f.getChildren()[i].position.y + f.getChildren()[i].width / 2 > y) {
                        //结束
                        isDie = true;
                    }
                }
            }
        }
        if (isDie == true) {
            //结算面版
            var overBg = this.node.getChildByName("overBg");
            overBg.active = true;
            overBg.getChildByName("curScore").getComponent(cc.Label).string = this.c_score;
            var maxScore_daxigua = cc.sys.localStorage.getItem('maxScore_daxigua');
            if (maxScore_daxigua == null || maxScore_daxigua == undefined) {
                maxScore_daxigua = 0;
            } else {
                maxScore_daxigua = parseInt(maxScore_daxigua);
            }
            if (maxScore_daxigua < this.c_score) {
                maxScore_daxigua = this.c_score;
            }
            cc.sys.localStorage.setItem('maxScore_daxigua', maxScore_daxigua);
            overBg.getChildByName("maxScore").getComponent(cc.Label).string = maxScore_daxigua;
        }
        return isDie;
    },


    // 创建一个水果
    createOneFruit: function createOneFruit(num) {
        var fruit = cc.instantiate(this.fruitPrefab);
        var config = this.fruits[num - 1];

        fruit.getComponent('Fruit').init({
            id: config.id,
            iconSF: config.iconSF
        });

        fruit.getComponent(cc.RigidBody).type = cc.RigidBodyType.Static;
        fruit.getComponent(cc.PhysicsCircleCollider).radius = 0;

        this.node.getChildByName("fruits").insertChild(fruit, this.node.getChildByName("fruits").childrenCount);
        // this.node.getChildByName("fruits").addChild(fruit);
        fruit.scale = 0.6;

        // 有Fruit组件传入
        fruit.on('sameContact', this.onSameFruitContact.bind(this));

        return fruit;
    },
    startFruitPhysics: function startFruitPhysics(fruit) {
        fruit.getComponent(cc.RigidBody).type = cc.RigidBodyType.Dynamic;
        var physicsCircleCollider = fruit.getComponent(cc.PhysicsCircleCollider);
        physicsCircleCollider.radius = fruit.height / 2;
        physicsCircleCollider.apply();
    },


    // 在指定位置生成水果
    createFruitOnPos: function createFruitOnPos(x, y) {
        var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

        var fruit = this.createOneFruit(type);
        fruit.setPosition(cc.v2(x, y));
        return fruit;
    },

    // 两个水果碰撞
    onSameFruitContact: function onSameFruitContact(_ref) {
        var self = _ref.self,
            other = _ref.other;

        other.node.off('sameContact'); // 两个node都会触发，todo 看看有没有其他方法只展示一次的

        var id = other.getComponent('Fruit').id;
        // todo 可以使用对象池回收
        self.node.removeFromParent(false);
        other.node.removeFromParent(false);

        var _other$node = other.node,
            x = _other$node.x,
            y = _other$node.y;


        this.createFruitJuice(id, cc.v2({ x: x, y: y }), other.node.width);
        console.log("合成了" + id, "分数+" + id + 1, "之前分数" + this.c_score);
        this.c_score += parseInt(id) + 1;
        this.refScore();

        if (id == 10) {
            this.playAnim();
        }

        var nextId = id + 1;
        if (nextId <= 11) {
            var newFruit = this.createFruitOnPos(x, y, nextId);

            this.startFruitPhysics(newFruit);
            // 展示动画 todo 动画效果需要调整
            newFruit.scale = 0;
            cc.tween(newFruit).to(.5, {
                scale: 0.6
            }, {
                easing: "backOut"
            }).start();
        } else {
            // todo 合成两个西瓜
            console.log(' todo 合成两个西瓜 还没有实现哦~ ');
        }
    },
    playAnim: function playAnim() {
        var xigua = this.node.getChildByName("xigua");
        xigua.active = true;
        xigua.getChildByName("con").scale = 0.1;

        var self = this;
        var callFunc = cc.callFunc(function () {
            xigua.active = false;
        });
        var action1 = cc.scaleTo(2, 1);
        var action2 = cc.scaleTo(2, 1);
        var se = cc.sequence(action1, action2, callFunc);
        xigua.getChildByName("con").runAction(se);
    },


    // 合并时的动画效果
    createFruitJuice: function createFruitJuice(id, pos, n) {
        // 播放合并的声音
        cc.audioEngine.play(this.boomAudio, false, 1);
        cc.audioEngine.play(this.waterAudio, false, 1);

        // 展示动画
        var juice = cc.instantiate(this.juicePrefab);
        this.node.addChild(juice);

        var config = this.juices[id - 1];
        var instance = juice.getComponent('Juice');
        instance.init(config);
        instance.showJuice(pos, n);
    },


    //3个道具 
    //随机打乱水果位置
    daojuAction1: function daojuAction1() {
        //查询所有水果，随机位置下落
        var f = this.node.getChildByName("fruits");
        var nodes = [];
        for (var i = 0; i < f.childrenCount; i++) {
            f.getChildren()[i].active = false;
            if (f.getChildren()[i].uuid != this.currentFruit.uuid) {
                nodes.push(f.getChildren()[i]);
            }
        }
        this.changeIndex(nodes);
    },
    changeIndex: function changeIndex(nodes) {
        var self = this;
        var t = nodes.length;
        this.schedule(function () {
            t--;
            if (t < 0) {
                self.currentFruit.active = true;
                self.isCreating = false;
                self.unscheduleAllCallbacks();
            } else {
                nodes[t].active = true;
                var size = cc.winSize;
                var y = size.height / 2 - 200;
                var x = self.random(-size.width / 2, size.width / 2);
                nodes[t].position = cc.v2(x, y);
            }
        }, 0.3);
    },
    sortArr: function sortArr(myarr) {
        var i = myarr.length;
        while (i) {
            var j = Math.floor(Math.random() * i--);
            myarr[i] = myarr[j];
            myarr[j] = myarr[i];
        }
    },
    random: function random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower + 1)) + lower;
    },
    daojuAction2: function daojuAction2() {
        this.isOpen_remove = true;
        this.node.getChildByName("background").getChildByName("right").active = false;
        this.node.getChildByName("background").getChildByName("score").active = false;
        this.node.getChildByName("background").getChildByName("tip").active = true;
    },
    cancelDaoju2: function cancelDaoju2() {
        this.isCreating = false;
        this.isOpen_remove = false;
        this.node.getChildByName("background").getChildByName("right").active = true;
        this.node.getChildByName("background").getChildByName("score").active = true;
        this.node.getChildByName("background").getChildByName("tip").active = false;
    },
    daojuAction3: function daojuAction3() {
        this.currentFruit.getChildByName("wanneng").active = true;
        this.currentFruit.getComponent("Fruit").resetSprite();
    },


    //over
    resetAction: function resetAction() {
        cc.director.loadScene("game", function () {});
    },
    goonAction: function goonAction() {
        this.node.getChildByName("overBg").active = false;
        this.node.getChildByName("fruits").removeAllChildren();
        var nextId = this.getNextFruitId();
        this.initOneFruit(nextId);
        this.isCreating = false;
    }
});

cc._RF.pop();